package chenjun.mydatabindingdemo.model;


import android.os.Handler;

import java.io.IOException;

import chenjun.mydatabindingdemo.constant.StringUrl;
import chenjun.mydatabindingdemo.view.OnShow;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by n6 on 2016/9/30.
 */
public class HttpUtil {

    private OkHttpClient okHttpClient = new OkHttpClient();
    private Handler handler = new Handler();
    private OnShow mOnShow;
    public HttpUtil(OnShow onShow){
        mOnShow = onShow;
    }

    public void downLoad(String url){
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                result.failure(e.getLocalizedMessage());
                mOnShow.failure();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String jsondata = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mOnShow != null){
                            mOnShow.show(jsondata);
                        }
                    }
                });
            }
        });
    }

}
